﻿@using MvcContrib.UI.Grid
@using XRM.Security.WebUI.Consts
@model XRM.Security.WebUI.Models.IdentityCenter.IdentityCenterModel
@{
    ViewBag.Title = String.Format("{0}", Model.IsEdit ? Model.IdentityCenterName : "Добавление УЦ");
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section styles
{
    <style type="text/css">
        .actions {
            border-top: 0;
            border-bottom: 1px solid #e5e5e5;
            padding: 0 0 15px 0;
        }
    </style>
}
@Html.Partial("ReturnLinkPartial", new Tuple<string, string>(Url.Action("Index"), "Вернуться к списку удостоверяющих центров"))

<div>
    @using (Html.BeginForm("Edit", "IdentityCenter", FormMethod.Post, new { @class = "form-horizontal form-horizontal-2" }))
    {
        @Html.AntiForgeryToken()

        const string inputCss = "form-control";
        const string divCss = "col-sm-4";

        @Html.HiddenFor(m => m.Id)
        @Html.HiddenFor(m => m.FileUploadUrl)
        @Html.HiddenFor(m => m.IdentityCenterName)
                
        <div class="form-group">
            @Html.LabelFor(m => m.IdentityCenterName, new { @class = "control-label required" })
            <div class="@divCss">
                @Html.TextBox("txtIdentityCenterName", Model.IdentityCenterName, new { @class = @inputCss, disabled = "disabled" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(m => m.Address, new { @class = "control-label" })
            <div class="@divCss">
                @Html.TextBoxFor(m => m.Address, new { @class = @inputCss })
                @Html.ValidationMessageFor(m => m.Address)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(m => m.Contact, new { @class = "control-label" })
            <div class="@divCss">
                @Html.TextBoxFor(m => m.Contact, new { @class = @inputCss })
                @Html.ValidationMessageFor(m => m.Contact)
            </div>
        </div>
                
        <div class="form-group">
            @Html.LabelFor(m => m.InfoSystemList, new { @class = "control-label" })
            <div class="@divCss">
                <div data-bind="template: { name: 'infosystem-template', foreach: InfoSystem }"></div>
                @if (!Model.ReadOnly)
                {
                    <div class="control-text">
                        <a href="#" data-bind="click: addInfoSystem">Добавить информационную систему</a>
                    </div>
                }
            </div>
        </div>
        
        if (!Model.ReadOnly)
        {
            @Html.Partial("_FormActionsPartial")
        }
    }
</div>

@if (!Model.ReadOnly)
{
    <div class="row">
        <form id="addCertForm" action="@Url.Action("AddCertificate")" method="POST">
            <div class="col-sm-offset-3 col-sm-6">
                @Html.Partial( "CertUploader", new ViewDataDictionary{{ViewDataConsts.Callback, "onCertUpload"}, {ViewDataConsts.UrlParameters, new {identityCenterId = Model.Id}}} )
                <input type="hidden" value="@Model.Id" name="identityCenterId"/>
            </div>
        </form>
    </div>
}
        
<script type="text/javascript">
    function onCertUpload() {
        $.post("@Url.Action("AddCertificate")", $("#addCertForm").serialize(), function (result) {
            if (result.isSuccess) {
                location.reload();
            }
            else {
                $("#certUploadErrorMessage").html(result.error);
            }
        });
    }
</script>

<h4>@Html.DisplayNameFor(m => m.FileList)</h4>

@if (Model.FileList.Any())
{       
    <div class="filtered-table">
        <div class="checkbox">
            <label for="@Model.ShowNotValidSert">
                @Html.CheckBoxFor(x => x.ShowNotValidSert, new { onclick="ShowNotValid()" })
                Отображать недействующие
            </label>
        </div>
    @{
        Html.Grid(Model.FileList).Columns(column =>
        {
        column.For(item => item.SerialNumber).Named("Серийный номер");
        column.For(item => item.ValidPeriod).Named("Срок действия");
        column.For(item => item.StatusCaption).Named("Статус");
        column.Custom
        (@<text>
              <a href="@Url.Action("DownloadIdentityCenterFile", new { id = item.Id })" title="Скачать"> <i class="fa fa-download fa-action"></i></a>
          </text>).Named( "<i class='fa fa-download fa-action'></i>" ).Attributes( @class => "single-action" );

        }).Attributes(@class => "table table-striped table-bordered", id => "table_id")
        .Render();
    }
    </div>
}
else
{
    <p>Сертификаты не загружены.</p>
}

<script type="text/html" id="infosystem-template">
    <div class="input-list-item" data-bind="css: { 'input-group': $index() >= 0 }">
        <select class="form-control" name="InfoSystemList[].Id" data-bind="attr: { name: 'InfoSystemList[' + $index() + '].Id' }, options: InfoSystemAll, optionsText: 'name', optionsValue: 'id', value: selectedValue"  />
        @if (!Model.ReadOnly)
        {
        <span class="input-group-btn" data-bind="">
            <button title="Удалить информационную систему" class="btn btn-default" type="button" data-bind="click: $parent.removeInfoSystem">
                <i class="fa fa-times"></i>
            </button>
        </span>
        }
    </div>
</script>

@section scripts
{
     @Scripts.Render("~/bundles/gridlibrary")
    <script type="text/javascript">
        function ShowNotValid() {
            if ($('#ShowNotValidSert').prop('checked')) {
                $("#table_id tr td:nth-child(3)").filter(function () { return $(this).text() === "Недействующий"; }).closest('tr').show();
            }
            else {
                $("#table_id tr td:nth-child(3)").filter(function () { return $(this).text() === "Недействующий"; }).closest('tr').hide();
            }
        }

        $(document).ready(function () {
            @if (Model.IsEdit)
            {
                if (Model.FileList.Any())
                {
                    <text>
                $('#table_id').dataTable({
                    paging: false,
                    bFilter: false,
                    bSort: false,
                    info: false,
                });
                ShowNotValid();
                </text>
                }
            }
        });
    </script>
    <script src="@Url.Content("~/Scripts/FileUploader.js")"></script>
    <script src="@Url.Content("~/Scripts/knockout-3.2.0.js")"></script>
    <script type="text/javascript">
        function IdentityCenterViewModel() {
            var self = this;

            self.InfoSystemAll = ko.observableArray([
                @{
                    if ((Model.InfoSystemAllList != null) && (Model.InfoSystemAllList.Any()))
                    {
                        foreach (var item in Model.InfoSystemAllList)
                        {
                            <text>{ id: '@item.Id', name: '@item.InfoSystemName.Replace("\\", "\\\\")' },</text>
                        }
                    }
                    else
                    {
                        <text>{ id: '-1', name: '' }</text>
                    }
                }
            ]);

            self.InfoSystem = ko.observableArray([
                @{
                    if ((Model.InfoSystemList != null) && (Model.InfoSystemList.Any()))
                    {
                        foreach (var item in Model.InfoSystemList)
                        {
                            <text>{ id: '@item.Id', name: '@item.InfoSystemName.Replace("\\", "\\\\")', InfoSystemAll: self.InfoSystemAll, selectedValue: '@item.Id' },</text>
                        }
                    }
                    else
                    {
                        <text></text>
                    }
                }
            ]);

            self.addInfoSystem = function () {
                self.InfoSystem.push({ id: "-1", name: "", InfoSystemAll: self.InfoSystemAll, selectedValue: '-1' });
            };

            self.removeInfoSystem = function () {
                self.InfoSystem.remove(this);
            };
        }

        ko.applyBindings(new IdentityCenterViewModel());

        $(document).ready(function () {
            @if (Model.ReadOnly)
            {
                <text>
                ReadOnlyView();
                $("#ShowNotValidSert").prop("disabled", false);
                </text>
            }
        });
    </script>
   
}